package net.begincode.SSO.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import net.begincode.SSO.bean.SsoUser;
import net.begincode.SSO.bean.Url;
import net.begincode.SSO.enums.UserResponse;
import net.begincode.SSO.exception.UserException;
import net.begincode.SSO.handler.UserHandler;

/**
 * 控制层
 * @author 遗忘
 * @date 2017.4.17
 *
 */
@Controller
@RequestMapping("/user")
public class UserController {
	@Resource
	private UserHandler handler;

	private Logger logger = LoggerFactory.getLogger("user");
	
	//用户注册
	@RequestMapping("/regist")
	public void regist(SsoUser user,HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		try {
			int state =  handler.regist(user);
			if(state==2){
				addTicket(response);
			}
			out.print("success");
			out.flush();
			out.close();
		} catch (UserException e) {
			logger.warn("用户注册失败");
			out.print(e.getMessage());
			out.flush();
			out.close();
		}
	}
	
	//用户登录
	@RequestMapping("/login")
	public void login(SsoUser user,HttpServletResponse response) throws IOException{
		PrintWriter out = response.getWriter();
		try {
			handler.login(user);
			addTicket(response);
			out.print("success");
			out.flush();
			out.close();
		} catch (UserException e){
			logger.warn("用户登录失败");
			out.print(e.getMessage());
			out.flush();
			out.close();
		}
	}
	
	//Ajax判断用户名是否存在
	@RequestMapping("/existEmail")
	public void existUsername(SsoUser user,HttpServletResponse response) throws IOException{
		PrintWriter out = response.getWriter();
		if(handler.existUsername(user.getEmail())){
			logger.info("该邮箱已注册");
			out.print(UserResponse.EMAILEXIST_ERROR.getMessage());
			out.flush();
			out.close();
		}else{
			out.print("false");
			out.flush();
			out.close();
		}
	}
	
	//添加cookie凭证  向redis中插入数据
	public void addTicket(HttpServletResponse response){
		String ticketCode = handler.intoRedis();
		Cookie cookie = new Cookie("ticket", ticketCode);
		cookie.setMaxAge(60*30);
		cookie.setPath("/");
		response.addCookie(cookie);
	}
	
	//提供给client的接口，验证登录状态
	@RequestMapping("/verify")
	public @ResponseBody String verify(Url url){
		if(handler.verifyLoginState(url)){
			return "true";
		}else{
			return "false";
		}
		
	}
	
	//全局注销接口
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request,HttpServletResponse response){
		Cookie[] cookies = request.getCookies();
		String redisKey = "";
		String logoutURL = "";
		String backURL = request.getRequestURL().toString();
		if(cookies!=null){
			for(Cookie cookie:cookies){
				if("ticket".equals(cookie.getName())){
					redisKey = cookie.getValue();
					logoutURL = handler.logoutAll(redisKey);
					if("none".equals(logoutURL)){
						cookie.setValue(null); 
						cookie.setPath("/");
						cookie.setMaxAge(0);
						response.addCookie(cookie);
						return "redirect:/core/login.jsp";
					}
					
				}
			}
		}
		return "redirect:"+logoutURL+"?backURL="+backURL;
	}
	
}
